﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ChaoDaoOs2
{
    public class OS2WeightService
    {
        private const int Brate = 9600; //波特率目前只支持9600
        static SensorDllCall.SensorInfo _sendorinfo;
        static SensorDllCall.IS1Info _is1Info;
        static Action<string> _callBack;

        public static string TipMessage { get; private set; }
        public static bool Init(string port, Action<string> callBack, UInt16 protecol = 1)
        {
            var isOk = ReSetCallback(callBack);
            if (!isOk)
            {
                TipMessage = "未设置回调方法";
                return false;
            }
            var isPortOpen = SensorDllCall.__Open(port, Brate);
            if (!isPortOpen)
            {
                TipMessage = "串口打开成功";
                return false;
            }
            var isProtecolOk = SetProtecol();
            if (!isProtecolOk)
            {
                TipMessage = "设置协议失败";
                return false;
            }
            return true;

        }
        /// <summary>
        /// 设置协议(默认设置1)
        /// </summary>
        /// <param name="val"></param>
        /// <returns></returns>
        public static bool SetProtecol(UInt16 val = 1)
        {
            if ((val == 1) | (val == 2) | (val == 3))
            {
                return SensorDllCall.__ChangeProtocol(val);
            }
            return false;
        }



        public enum Unit
        {
            G = 0,//"公克"
            Kg = 1,//"公斤"
            T = 2, //"公吨"
            FenHK = 3,//"分(香港)"
            QianHK = 4,//"钱(香港)"
            LiangHK = 5,//"两(香港)"
            JinHK = 6,//"斤(香港)"
            DanHK = 7, //"担(香港)"
            FenTaiWan = 8,//"分(台湾)"
            QianTaiWan = 9, //"钱(台湾)"
            LiangTaiWan = 10,//"两(台湾)"
            JinTaiWan = 11,//"斤(台湾)"
            DanTaiWan = 12, //"担(台湾)"
            GuSi = 13, //"盎司"
            Pound = 14,//"磅"
            Kilopound = 15//"千磅"
        }

        /// <summary>
        /// 设置单位
        /// </summary>
        /// <param name="unit"></param>
        /// <returns></returns>
        public static bool SetUnit(Unit unit = Unit.Kg)
        {
            return SensorDllCall.__SetUnitValue((UInt16)unit, "1234");
        }

        private static bool ReSetCallback(Action<string> callback)
        {
            if (callback == null) return false;
            _callBack = callback;
            _sendorinfo = DisplaySensorInfo;
            SensorDllCall.__SetCallBackFunc("SENSORINFO", _sendorinfo);
            _is1Info = DisplayIS1Info;
            SensorDllCall.__SetCallBackFunc("IS1INFO", _is1Info);
            return true;
        }

        public static void Close()
        {
            TipMessage = "";
            SensorDllCall.__Close();
        }

        #region 主动称重
        private void Weight()
        {
            SensorDllCall.__Weight("1234");
        }


        //     返回值: (1.空，2.数据)

        //数据格式:
        //    status,sign,Weight,AUnit,flag
        //    status说明:
        //        status = 'F'   // '重量溢出或没有开机归零';
        //        status = 'S'   // '重量稳定';
        //        fstatus= 'U'   // '重量不稳定';

        //完整重量显示说明:
        //    sign+Weight+AUnit

        //flag说明:
        //    flag = 16; //已归零
        //    flag = 30; //已去皮
        /// <summary>
        /// 获取重量
        /// </summary>
        private void GetWeight()
        {

            var sRet = new StringBuilder(256);
            bool bRet = SensorDllCall.__GetWeightEx(ref sRet);
            if (!bRet) return;
            if (sRet == null) return;
            var result = sRet.ToString();
            var retArray = result.Split(',');
            if (retArray.Length != 5) return;
            var status = retArray[0];
            var sign = retArray[1];
            var weight = retArray[2];

        }
        #endregion

        #region 回调
        //double NetWeight: 净重
        //double Tare: 皮重
        //double Grossweight: 毛重
        //int Mode: 模式
        //int DecimalDigit: 小数位数
        //int UnitChar: 重量单位
        //int OldAd, int FilterAd, int ZeroAd, int WeightAd: 保留
        //int flag:
        //   Bit0: 0表示重量不稳定            1表示重量稳定
        //   Bit1: 0表示重量没有溢出          1表示重量溢出
        //   Bit2: 0表示有开机归零            1表示没有开机归零
        //   Bit3: 0当前重量大于最小称量范围  1当前重量小于最小称量范围
        //   Bit4: 1当前OP盒被软解锁         0当前OP盒没有软解锁
        //   Bit5: 1当前OP盒硬件解锁         0当前OP盒硬件没解锁
        //   Bit6: 1结果的最低位永远为零		  0结果的最低位可能非零
        public static void DisplaySensorInfo(double netWeight, double tare, double grossweight, int mode, int decimalDigit, int unitChar,
                             int oldAd, int filterAd, int zeroAd, int weightAd, int flag)
        {
            bool isNewWeightCanRet = true;
            TipMessage = "";
            if ((flag & 0x01) != 0x01)
            {
                //重量不稳定
                TipMessage += "重量不稳定" + Environment.NewLine;
            }


            if ((flag & 0x02) == 0x02)
            {
                isNewWeightCanRet = false;
                //重量溢出
                TipMessage += "重量溢出" + Environment.NewLine;
            }


            if ((flag & 0x04) == 0x04)
            {
                //没有开机归零
                TipMessage += "没有开机归零" + Environment.NewLine;
            }


            if ((flag & 0x08) == 0x08)
            {
                //当前重量小于最小称量范围
                TipMessage += "当前重量小于最小称量范围" + Environment.NewLine;
            }


            if ((flag & 0x10) == 0x10)
            {
                //当前OP盒被软解锁
                TipMessage = "当前OP盒被软解锁" + Environment.NewLine;
            }
            else
            {
                //当前OP盒没有软解锁
                TipMessage = "当前OP盒没有软解锁" + Environment.NewLine;
            }

            if ((flag & 0x20) == 0x20)
            {
                //当前OP盒硬件解锁
                TipMessage = "当前OP盒硬件解锁" + Environment.NewLine;
            }
            else
            {
                //当前OP盒硬件没解锁
                TipMessage = "当前OP盒硬件没解锁" + Environment.NewLine;
            }

            if ((flag & 0x40) == 0x40)
            {
                //结果的最低位永远为零
                TipMessage = "结果的最低位永远为零" + Environment.NewLine;
            }
            else
            {
                //结果的最低位可能非零
                TipMessage = "结果的最低位可能非零" + Environment.NewLine;
            }
            if (!isNewWeightCanRet)
            {
                if (_callBack != null) _callBack("0");
                return;
            }
            if (_callBack != null) _callBack(netWeight.ToString());
            //switch (Mode)
            //{
            //    case 0:
            //        {
            //            weightlbl.Text = NetWeight.ToString(sfor) + " " + unitval;
            //            Tarelbl.Text = "0.00";
            //            Grossweightlbl.Text = "0.00";
            //            break;
            //        }
            //    case 1:
            //    case 2:
            //        {
            //            weightlbl.Text = NetWeight.ToString(sfor) + " " + unitval;
            //            Tarelbl.Text = Tare.ToString(sfor) + " " + unitval;
            //            Grossweightlbl.Text = Grossweight.ToString(sfor) + " " + unitval;
            //            if (Mode == 2)
            //            {
            //                label4.Text = "预制皮重:";
            //            }
            //            else
            //            {
            //                label4.Text = "皮重:";
            //            }
            //            break;
            //        }
            //}


            //if (flagMode == 0xFF)
            //{
            //    weightlbl.Text = "-----";
            //    Tarelbl.Text = "-----";
            //    Grossweightlbl.Text = "-----";

            //}

        }

        public static void DisplayIS1Info(string status, string sign, string weight, string fUnit, int flag)
        {
            bool isWeightCanRet = true;
            TipMessage = "";
            if (status == "F")
            {
                isWeightCanRet = false;
                TipMessage += "重量溢出或没有开机归零";
            }

            if (status == "U")
            {
                TipMessage += "重量不稳定";
            }
            if (!isWeightCanRet)
            {
                if (_callBack != null) _callBack("0");
                return;
            }
            string fweight = sign + weight;
            //fweight = fweight + fUnit;
            if (_callBack != null) _callBack(fweight);

        }
        #endregion
    }

}
